// app.js
import env from "./utils/env"
App({
  data: {
    // userInfo: {},
    // getUserInfo: false,
    defaultAvatarUrl : 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
  },
  userInfo:{
    nickName:'',
    avatarUrl:''
  },
  globalData:{
    openid:''
  },
  onLaunch: function (options) {
      // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    const scene = decodeURIComponent(options.query.scene);
    wx.setStorageSync('parentOpenID', scene);
    let userInfo = wx.getStorageSync('userInfo');
      if (!userInfo){
        wx.setStorage({
          key:'userInfo',
            data:{avatarUrl:'/image/avatarUrl.png'
            }
        })
      }
  wx.checkSession({
    fail () {
      wx.login({
        success: (res) => {
        const {code} = res.code
        wx.setStorageSync('code', res.code)
          console.log("获取并缓存code:", res.code)
            if (res) { 
              wx.request({
                url: '你的服务器API地址',
                method: 'POST',
                data: { code: res.code },
                header:{'content-Type': 'application/x-www-form-urlencoded;charset=utf-8',},
                  success:res=> {              
                    console.log("后端:openid:", res.data) 
                    let openid = res.data
                    const app = getApp()
                    getApp().globalData.openid = openid                                        
                    console.log('缓存openid:',app.globalData.openid)           
                    wx.setStorageSync('openid', res.data)                                             
                  }
              })
            } else {
              console.log('登录失败！' + res.errMsg)
            }
        }
      })
        console.log("session_key 已经失效，重新登陆获取流程")
      }
    })
  },
  login: function () {
    //调用登录
    let that = this;
    wx.login({
      success: function (res) {
        var parentOpenID = wx.getStorageSync('parentOpenID');
        console.log(parentOpenID);
        if (res.code) {
          //发起网络请求
          wx.request({
            url: env.api_host + '/auth/miniLogin',
            data: {
              jsCode: res.code,
              username: parentOpenID
            },
            method: 'POST',
            header: { 'content-type': 'application/json' },
            success: function (data) {
              if (data.data.code == 200) {
                wx.setStorageSync('is_login', true);
                wx.setStorageSync('third_session', data.data.data.third_session);
                wx.setStorageSync('access_token', data.data.data.access_token);
                wx.getSetting({
                  success(res) {
                    if (res.authSetting['scope.userInfo']) {
                      // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                      wx.getUserInfo({
                        success(res) {
                          // console.log(res);
                          // console.log(res.userInfo.nickName);
                          that.setData({
                            is_login: true,
                            nickName: res.userInfo.nickName
                          });
                        }
                      })
                    }
                  }
                })
                that.getHistoryInfo();
              }
            },
            fail: function (data) {
              console.log(data);
            },
            complete: function (data) {
              console.log(data);
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail: function () {
        console.log("启用wx.login函数，失败！");
      },
      complete: function () {
        console.log("已启用wx.login函数");
      }
    })
  },
})
